<script setup>
import {ref, watch} from 'vue'

const question = ref('?')
const isrc = ref('')
const flag = ref(false)
const answer = ref('Questions usually contain a question mark. ;-)')

// 可以直接侦听一个 ref
watch(question, async (newQuestion, oldQuestion) => {
  if (newQuestion.indexOf('?') > -1) {
    answer.value = 'Thinking...'
    try {
      const res = await fetch('https://yesno.wtf/api')
      let result = await res.json()
      answer.value = result.answer
      isrc.value = result.image
      flag.value = true
    } catch (error) {
      answer.value = 'Error! Could not reach the API. ' + error
    }
  }
}, {immediate: true, deep: true})
</script>

<style scoped>
img {
  width: 200px;
  border: 1px dashed gray;
  padding: 5px;
  border-radius: 15px;
}
</style>

<template>
  <p>
    Ask a yes/no question:
    <input v-model="question"/>
  </p>
  <p>{{ answer }}</p>
  <br>
  <div><img :src="isrc" v-show="flag" alt=""></div>
</template>
